var pageNum = 15;// 每页加载的条数
$(function() {
	loadMainList();
	loadComment();
	rollingLoad();// 滚动加载
	$.mCustomScrollbar.defaults.theme = "light-2"; // set "light-2" as the//
	// default theme
	/*
	 * $("#ho1,#ho2").mCustomScrollbar({ axis : "x", advanced : {
	 * autoExpandHorizontalScroll : true } });
	 */
	downRefresh();// 下拉刷新
});
function loadForumArticle(userId){
	var preUrl = window.location.href;
	localStorage.setItem('forum_user_preUrl', preUrl);
	lh.jumpR("/forumUserArticle/"+userId);
}
// 下拉刷新
function downRefresh() {
	$("#weui-layer").show();
	$(document.body).pullToRefresh();
	$(document.body).on("pull-to-refresh", function() {
		lh.reload();
	});
	$(document.body).pullToRefreshDone();
}
// 滚动加载
function rollingLoad() {
	var loading = false; // 状态标记
	$(document.body).infinite().on("infinite", function() {
		if (loading)
			return;
		loading = true;
		setTimeout(function() {
			// $(document.body).destroyInfinite();
			// $(".weui-infinite-scroll").hide();
			loadComment();
			loading = false;
		}, 1000); // 模拟延迟
	});
}

function showImgs(picPaths) {
	var pics = picPaths.split(',');
	var pb1 = $.photoBrowser({
		items : pics
	});
	pb1.open();
}

function loadMainList() {
	var forumArticleId = lh.param.forumArticleId;
	var param = {
		forumArticleId : forumArticleId
	};
	lh.post('front', '/getForumDetail', param, function(rsp) {
		var data = rsp.forumArticle;
		makeMainListDom(data, true);
		lh.page.currentPage++;
	}, 'json');
}
function loadComment(isAppend) {
	if(isAppend !== false){
		isAppend = true;
	}
	var forumArticleId = lh.param.forumArticleId;
	var commentTypeCode = "comment_forumArticle";
	lh.post('front', '/getCommentList', {
		page : lh.page.currentPage,
		rows : 20,
		forumArticleId : forumArticleId,
		commentTypeCode : commentTypeCode,
		forumName : 1
	}, function(rsp) {
		if (rsp.success) {
			var data1 = rsp;
			$("#comenttotal").html("全部跟帖（" + rsp.total + "）");

			makeMainListDoms(data1, isAppend);
			lh.page.currentPage++;

		} else {
			lh.page.currentPage = 1;
			$('#resultTip').text(rsp.msg).show();
			$(".weui-infinite-scroll").text('没有更多数据');
			lh.alert(rsp.msg);
		}
	}, 'json');
}

function renderEvent() {
	$("#data-container .scrollbar_ul").mCustomScrollbar({
		axis : "x",
		advanced : {
			autoExpandHorizontalScroll : true
		}
	});
}

function makeMainListDom(mainList, isAppend) {
	var template = $('#template').html();

	Mustache.parse(template); // optional, speeds up future uses
	var rendered = Mustache.render(template, {
		rows : mainList,
		picsDom : function() {
			var picPaths = this.picPaths;
			if (!picPaths)
				return '';
			var pics = picPaths.split(',');
			var length = pics.length;
			// if(length > 9)length = 9;
			var picsDom = '';
			for (var i = 0; i < length; i++) {
				var pic = pics[i];
				pic += buildOSSZoom(500, 300); // @@_OSS_IMG_@@
				picsDom += '<div  width="150%" height="150px" style="margin-top: 15px;"  ><img src="' + pic
						+ '"  width="150%" height="150px" ></div>';
			}
			return picsDom;
		},
		getDate : function() {
			var createdAt = this.createdAt;
			createdAt = lh.formatDate({
				date : new Date(createdAt),
				flag : 'datetime'
			});
			return createdAt;
		},
		titles:function(){
			var typeCode = this.typeCode;
			var titles = '';
			if(typeCode == 'shaihaowu'){
				titles = '晒好物:'+this.title;
			}else{
				titles = '话题:'+this.title;
			}
			return titles;
		},
		shai:function(){
			var typeCode = this.typeCode;
			var shai = '';
			if(typeCode == 'shaihaowu'){
				var goodsName = getOrderGoods(this.typeId,this.id);
				shai = "晒好物自:<span id='showGoodsName_"+this.id+"'></span><br/>" +
						"<img height='100px' width='100px' src='' id='showImg_"+this.id+"'></img>";
			}
			return shai;
		}	
	});
	if (isAppend) {
		$('#forumDetailInfo').append(rendered);
	} else {
		$('forumDetailInfo').html(rendered);
	}
	renderEvent();
	checkDom();
}
function getOrderGoods(goodsId,ids){
	var parmar = {id:goodsId};
		lh.post('front', '/getOrderGoodsById', parmar, function(rsp) {
			$("#showGoodsName_"+ids).text(rsp.orderGoods.goodsName);
			$("#showImg_"+ids).attr("src",rsp.orderGoods.picPath+=buildOSSZoom(70, 70));
		},'json');
}

function checkDom() {
	var domNum = $(".mt6").size()
	if (domNum >= 100) {
		$(".mt6:lt(20)").remove();
	}
	if (domNum < 15) {
		$(".weui-infinite-scroll").text("没有更多数据");
	}
}
function makeMainListDoms(mainList, isAppend) {
	var template = $('#template2').html();
	Mustache.parse(template); // optional, speeds up future uses
	var rendered = Mustache.render(template, {
		rows : mainList.rows,
		total : mainList.total,
		getDate : function() {
			var createdAt = this.createdAt;
			createdAt = lh.formatDate({
				date : new Date(createdAt),
				flag : 'datetime'
			});
			return createdAt;
		}
	});
	if (isAppend) {
		$('#coment').append(rendered);
	} else {
		$('#coment').html(rendered);
	}
	renderEvent();
}
SAVING_FLAG = false;

function addPraise() {
	var params = {
		praiseId : objectId,
		praiseType : 1
	};
	lh.post('front', '/addUserPraise', params, function(rsp) {
		if (rsp.success == "success") {
			if (rsp.code == 'alreadyExist_error') {
				lh.alert('已经点过赞了');
				return;
			}
		} else {
			lh.alert(rsp.msg);
		}
	});
}

function addComment() {
	var content = $("#content").val();
	var username = $("#username").val();
	var userId = $("#userId").val();
	var objectId = lh.param.forumArticleId;
	if (SAVING_FLAG)
		return;
	SAVING_FLAG = true;
	if (!content) {
		lh.alert('请填写评论的内容');
		SAVING_FLAG = false;
		return;
	}
	var obj = {};
	// obj.commentTypeId = commentTypeId;
	obj.content = content;
	obj.objectId = objectId;
	obj.username = username;
	obj.userId = userId;
	obj.commentTypeCode = "comment_forumArticle";
	// frontBaseLoadingOpen('正在保存数据...');//加载遮罩
	$.post('/comment/addOrUpdateComment', obj, function(rsp) {
		SAVING_FLAG = false;
		// frontBaseLoadingClose();//解除遮罩
		if (rsp) {
			frontLoginCheck(rsp);// 登陆检查
			if (rsp.status == 'success') {
				var content = $("#content").val("");
				lh.page.currentPage = 1;
				loadComment(false);
			} else {
				if (rsp.noPhone == 'noPhone') {
					lh.alert(rsp.msg, "jumpToBindUserPhone()");
				} else {
					lh.alert(rsp.msg);
				}
			}
		}
	}, 'json');

}
